package com.cyf.Coupon.service.impl;

import com.alibaba.fastjson.JSON;
import com.cyf.Coupon.service.CouponService;
import com.cyf.activemq.network.bean.MqBusinessOpt;
import com.cyf.activemq.network.bean.MqSendCouponReq;
import com.cyf.activemq.service.MqService;
import com.cyf.activemq.service.SendMsgService;
import com.cyf.app.network.bean.AppBusinessRsp;
import com.cyf.db.bean.*;
import com.cyf.db.mapper.*;
import com.cyf.merchat.network.bean.*;
import com.cyf.service.AppUserCarService;
import com.cyf.service.PayOrderService;
import com.cyf.util.DateUtil;
import com.cyf.util.HttpUtils;
import com.cyf.util.ObjectMapperUtils;
import com.cyf.util.WeChatSubscriptionUtil;
import com.cyf.wechat.network.bean.GetOpenidRsp;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
public class CouponServiceImpl implements CouponService {
    private static final Logger logger = LoggerFactory.getLogger(CouponServiceImpl.class);
    @Autowired
    private AppUserCarService appUserCarService;
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private MerchantCouponMapper merchantCouponMapper;
    @Autowired
    private WeChatSubscriptionUtil weChatSubscriptionUtil;
    @Autowired
    private UsersWechatMapper usersWechatMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ParkingMapper parkingMapper;
    @Autowired
    private MqService mqService;

    @Override
    public MerchantCouponLssueRecordRsp userIssueRecord(UserIssueRecordReq req) {
        MerchantCouponLssueRecordRsp rsp = new MerchantCouponLssueRecordRsp();
        try {
            logger.info("当前订单号{}"+req.getOrderNo());
            //根据订单号查询订单信息
            PayOrder payOrder = payOrderService.selectByOrderNo(req.getOrderNo());
            if (payOrder == null) {
                rsp.setResult(MerchantBusinessRsp.FAIL);
                rsp.setStrError("没有查到此订单信息！");
                return rsp;
            }
            //根据车牌号获取车主的手机号
            String moblie = appUserCarService.selectByPlate(payOrder.getPlate());
            //根据手机号查询可用的优惠券
            if (StringUtils.isNotEmpty(moblie)) {
                logger.info("获取的车主手机号{}"+moblie);
                req.setPlate(payOrder.getPlate());
                req.setPhone(moblie);
                req.setParkingId(payOrder.getParkingId());
                logger.info("当前车场id{}"+payOrder.getParkingId());
                req.setEndTime(DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                List<MerchantCouponVo> merchantCouponVoList = new ArrayList<MerchantCouponVo>();
                //统计用户在当前车场可用的优惠券个数
                int countMerchantCoupon = merchantCouponMapper.countMerchantCoupon(req);
                logger.info("用户在当前车场可用的优惠券个数{}"+countMerchantCoupon);
                //查询用户在当前车场可用的优惠券
                List<MerchantCoupon> merchantCouponList = merchantCouponMapper.selectByMobile(req);
                for (MerchantCoupon merchantCoupon : merchantCouponList) {
                    logger.info("优惠券id{}"+merchantCoupon.getId());
                    MerchantCouponVo merchantCouponVo = new MerchantCouponVo();
                    merchantCouponVo.setId(merchantCoupon.getId());
                    merchantCouponVo.setStatus(merchantCoupon.getStatus());
                    merchantCouponVo.setCreatedTime(DateUtil.formatDate(merchantCoupon.getCreatedTime(), "yyyy-MM-dd"));
                    if (merchantCoupon.getCouponType() != null) {
                        merchantCouponVo.setCouponType(merchantCoupon.getCouponType());
                    }
                    merchantCouponVo.setDiscount(merchantCoupon.getDiscount());
                    if (merchantCoupon.getFreeAmount() != null) {
                        merchantCouponVo.setFreeAmount(merchantCoupon.getFreeAmount());
                    }
                    if (merchantCoupon.getFreeHours() != null) {
                        merchantCouponVo.setFreeHours(merchantCoupon.getFreeHours());
                    }
                    merchantCouponVo.setParkingId(merchantCoupon.getParkingId());
                    merchantCouponVo.setUseWay(merchantCoupon.getUseWay());
                    merchantCouponVo.setParkingName(merchantCoupon.getParkingName());
                    merchantCouponVo.setEndTime(DateUtil.formatDate(merchantCoupon.getEndTime(), "yyyy-MM-dd"));
                    merchantCouponVoList.add(merchantCouponVo);
                }
                rsp.setCouponList(merchantCouponVoList);
                rsp.setTotal(countMerchantCoupon);
            }
            rsp.setResult(MerchantCouponLssueRecordRsp.SUCCESS);
            rsp.setActualFee(payOrder.getFee());
        } catch (Exception e) {
            rsp.setResult(MerchantBusinessRsp.FAIL);
            rsp.setStrError("获取车主优惠券列表异常！");
            e.printStackTrace();
            logger.error("获取车主优惠券列表异常{}", e.getMessage());
        }
        return rsp;
    }

    @Override
    public MerchantCouponLssueRecordRsp userIssueRecordFuMao(String orderNo) {
        MerchantCouponLssueRecordRsp rsp = new MerchantCouponLssueRecordRsp();
        UserIssueRecordReq req = new UserIssueRecordReq();
        try {
            logger.info("富茂当前订单号{}"+orderNo);
            //根据订单号查询订单信息
            PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);
            if (payOrder == null) {
                rsp.setResult(MerchantBusinessRsp.FAIL);
                rsp.setStrError("没有查到此订单信息！");
                return rsp;
            }
            //根据车牌号查询可用的优惠券
            if (StringUtils.isNotEmpty(payOrder.getPlate())) {
                req.setPlate(payOrder.getPlate());
                req.setParkingId(payOrder.getParkingId());
                logger.info("当前车场id{},当前的车牌号{}",payOrder.getParkingId(),payOrder.getPlate());
                req.setEndTime(DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                List<MerchantCouponVo> merchantCouponVoList = new ArrayList<MerchantCouponVo>();
                //统计用户在当前车场可用的优惠券个数
                int countMerchantCoupon = merchantCouponMapper.countMerchantCoupon(req);
                logger.info("用户在当前车场可用的优惠券个数{}"+countMerchantCoupon);
                //查询用户在当前车场可用的优惠券
                List<MerchantCoupon> merchantCouponList = merchantCouponMapper.selectByMobile(req);
                for (MerchantCoupon merchantCoupon : merchantCouponList) {
                    logger.info("优惠券id{}"+merchantCoupon.getId());
                    MerchantCouponVo merchantCouponVo = new MerchantCouponVo();
                    merchantCouponVo.setId(merchantCoupon.getId());
                    merchantCouponVo.setStatus(merchantCoupon.getStatus());
                    merchantCouponVo.setCreatedTime(DateUtil.formatDate(merchantCoupon.getCreatedTime(), "yyyy-MM-dd"));
                    if (merchantCoupon.getCouponType() != null) {
                        merchantCouponVo.setCouponType(merchantCoupon.getCouponType());
                    }
                    merchantCouponVo.setDiscount(merchantCoupon.getDiscount());
                    if (merchantCoupon.getFreeAmount() != null) {
                        merchantCouponVo.setFreeAmount(merchantCoupon.getFreeAmount());
                    }
                    if (merchantCoupon.getFreeHours() != null) {
                        merchantCouponVo.setFreeHours(merchantCoupon.getFreeHours());
                    }
                    merchantCouponVo.setParkingId(merchantCoupon.getParkingId());
                    merchantCouponVo.setParkingName(merchantCoupon.getParkingName());
                    merchantCouponVo.setUseWay(merchantCoupon.getUseWay());
                    merchantCouponVo.setEndTime(DateUtil.formatDate(merchantCoupon.getEndTime(), "yyyy-MM-dd"));
                    merchantCouponVoList.add(merchantCouponVo);
                }
                rsp.setCouponList(merchantCouponVoList);
                rsp.setTotal(countMerchantCoupon);
            }
            rsp.setResult(MerchantCouponLssueRecordRsp.SUCCESS);
            rsp.setActualFee(payOrder.getFee());
        } catch (Exception e) {
            rsp.setResult(MerchantBusinessRsp.FAIL);
            rsp.setStrError("富茂获取车主优惠券列表异常！");
            e.printStackTrace();
            logger.error("富茂获取车主优惠券列表异常{}", e.getMessage());
        }
        return rsp;
    }

    @Override
    public MerchantCouponLssueRecordRsp userCoupon(String openId, int status,String phone) {
        MerchantCouponLssueRecordRsp rsp = new MerchantCouponLssueRecordRsp();
        try {
            User user = null;
//            根据openid获取用户id
            if(StringUtils.isNotBlank(phone)){
                user = userMapper.getByMobile(phone);
            }else {
              UsersWechat usersWechat = usersWechatMapper.getByOpenid(openId);
                if (usersWechat == null) {
                    rsp.setResult(AppBusinessRsp.FAIL);
                    rsp.setStrError("获取用户信息失败!");
                    return rsp;
                }
                user = userMapper.getById(usersWechat.getUserId());
            }

            //根据用户id查询users


            if (user != null) {
                List<MerchantCouponVo> merchantCouponVoList = new ArrayList<MerchantCouponVo>();
                String date = null;//DateUtil.formatDate(new Date(), "yyyy-MM-dd");
                //根据手机号查询车主的优惠券列表
                List<MerchantCoupon> merchantCouponList = merchantCouponMapper.selectCouponByMobile(user.getMobile(), date, status);
                for (MerchantCoupon merchantCoupon : merchantCouponList) {
                    MerchantCouponVo merchantCouponVo = new MerchantCouponVo();
                    merchantCouponVo.setId(merchantCoupon.getId());
                    merchantCouponVo.setStatus(merchantCoupon.getStatus());
                    merchantCouponVo.setCreatedTime(DateUtil.formatDate(merchantCoupon.getCreatedTime(), "yyyy-MM-dd"));
                   if(merchantCoupon.getTimespent()!= null){
                       merchantCouponVo.setTimespent(DateUtil.formatDate(merchantCoupon.getTimespent(), "yyyy-MM-dd"));
                   }
                    if (merchantCoupon.getCouponType() != null) {
                        merchantCouponVo.setCouponType(merchantCoupon.getCouponType());
                    }
                    merchantCouponVo.setDiscount(merchantCoupon.getDiscount());
                    if (merchantCoupon.getFreeAmount() != null) {
                        merchantCouponVo.setFreeAmount(merchantCoupon.getFreeAmount());
                    }
                    if (merchantCoupon.getFreeHours() != null) {
                        merchantCouponVo.setFreeHours(merchantCoupon.getFreeHours());
                    }
                    merchantCouponVo.setParkingId(merchantCoupon.getParkingId());
                    merchantCouponVo.setUseWay(merchantCoupon.getUseWay());
                    merchantCouponVo.setParkingName(merchantCoupon.getParkingName());
                    merchantCouponVo.setEndTime(DateUtil.formatDate(merchantCoupon.getEndTime(), "yyyy-MM-dd"));
                    merchantCouponVoList.add(merchantCouponVo);
                }
                //全部优惠券
                int couponTotal = merchantCouponMapper.countCouponTotal(user.getMobile(), date, status);
                rsp.setCouponTotal(couponTotal);
                //已使用的优惠券
                int couponUse = merchantCouponMapper.countCouponUse(user.getMobile(), date);
                rsp.setCouponUser(couponUse);
                rsp.setCouponList(merchantCouponVoList);
                rsp.setResult(MerchantBusinessRsp.SUCCESS);
            }
        } catch (Exception e) {
            rsp.setResult(MerchantBusinessRsp.FAIL);
            rsp.setStrError("车主获取全部车场优惠券列表异常！");
            logger.error("车主获取全部车场优惠券列表异常{}", e.getMessage());
        }
        return rsp;
    }

    @Override
    public MerchantBusinessRsp couponUse(Integer[] couponId, String orderNo) {
        MerchantBusinessRsp rsp = new MerchantBusinessRsp();
        try {
            List<Integer> couponIds = new ArrayList<>();
            if (couponId != null && couponId.length > 0) {
                couponIds = Arrays.stream(couponId).collect(Collectors.toList());
                Date date = new Date();
                String ids = "";
                List<MerchantCoupon> merchantCouponList = merchantCouponMapper.selectByIds(couponIds);
                //查询使用的优惠券列表
                int couponFee = 0;
                for (MerchantCoupon merchantCoupon : merchantCouponList) {
                    logger.info("优惠券支付的id{}", merchantCoupon.getId());
                    couponFee += merchantCoupon.getFreeAmount();
                    ids += merchantCoupon.getId()+",";
                }
                PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);
                if (payOrder == null) {
                    rsp.setResult(MerchantBusinessRsp.FAIL);
                    rsp.setStrError("非法操作，请重新扫码进行支付！");
                    return rsp;
                }
                int shouldFee = payOrder.getFee();
                int ys = payOrder.getFee();
                int actualFee = 0;
                if (couponFee < payOrder.getFee()) {
                    actualFee = payOrder.getFee() - couponFee;
                    if (actualFee < 0) {
                        actualFee = 0;
                    }
                }
                int i = 0;
                for (MerchantCoupon m : merchantCouponList) {

                    if (shouldFee >= m.getFreeAmount()) {
                        merchantCouponMapper.updateCoupon(m.getId(), date, ys, m.getFreeAmount(), actualFee);
                    } else if (shouldFee < m.getFreeAmount() && shouldFee != 0) {
                        merchantCouponMapper.updateCoupon(m.getId(), date, ys, shouldFee, actualFee);
                    } else if (shouldFee == 0) {
                        merchantCouponMapper.updateCoupon(m.getId(), date, ys, shouldFee, actualFee);
                    }
                    shouldFee = shouldFee - m.getFreeAmount();
                    if (shouldFee < 0) {
                        shouldFee = 0;
                    }
                    ys = 0;
                    actualFee = 0;
                }
                if (couponFee >= payOrder.getFee()) {
                    Date payTime = new Date();
                    couponFee = payOrder.getShouldFee();
                    //如果支付0元时，修改支付状态
                    payOrderService.updatePayOrderPayStatus(couponId[0], orderNo, couponFee, payTime,ids);
                    //支付结果下发车场
                    PayOrder order = payOrderService.selectByOrderNo(orderNo);
                    mqService.sendPayOrder(order);
                    logger.info("优惠券支付成功优惠金额{"+couponFee+"}实收金额{"+payOrder.getFee()+"}");
                    logger.info("优惠券支付，下发优惠券支付结果成功！优惠券：Id：{},优惠金额：{}", orderNo);
                } else {
                    //调用微信支付宝应收的金额
                    int fee = payOrder.getFee() - couponFee;
                    //优惠总金额
                    int couponFeeTotal = payOrder.getShouldFee() - fee;
                    //修改payorder表的信息
                    payOrderService.updatePayOrderCouponId(couponId[0], orderNo, couponFeeTotal, fee,ids);
                    //支付结果下发车场
                    PayOrder order = payOrderService.selectByOrderNo(orderNo);
                    mqService.sendPayOrder(order);
                    logger.info("优惠券支付成功优惠金额{"+couponFee+"}实收金额{"+payOrder.getFee()+"}需要支付{"+fee+"}");
                }
                //如果是富茂的车场   就推送优惠券id
                if(payOrder.getParkingId() == 1461){
                    String json = JSON.toJSONString(couponIds);
                    String result = HttpUtils.postJson("127.0.0.1:8888",json);
                    logger.info("向富茂推送使用过的优惠券id{}",json);
                }
            }
            rsp.setResult(MerchantCouponLssueRecordRsp.SUCCESS);
            rsp.setCouponIds(Arrays.asList(couponId));

        } catch (Exception e) {
            rsp.setResult(MerchantBusinessRsp.FAIL);
            rsp.setStrError("修改优惠券状态异常！");
            logger.error("修改优惠券状态异常{}", e.getMessage());
        }
        return rsp;
    }

    @Override
    public PaySuccessRsp paySuccessInfo(String orderNo) {
        PaySuccessRsp rsp = new PaySuccessRsp();
        try {
            PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);
            Parking parkingById = parkingMapper.getParkingById(payOrder.getParkingId());
            rsp.setCouponFee(payOrder.getCouponFee());
            rsp.setParkingId(payOrder.getParkingId());
            rsp.setParkingName(parkingById.getName());
            rsp.setActualFee(payOrder.getActualFee());
            rsp.setPlate(payOrder.getPlate());
            rsp.setRecordOrderId(payOrder.getRecordOrderId());
            if (payOrder.getPayTime() != null) {
                rsp.setFeeEndTime(DateUtil.formatDate(payOrder.getPayTime(), "yyyy-MM-dd HH:mm:ss"));
            }
            if (payOrder.getIntoTime() != null) {
                rsp.setIntoTime(DateUtil.formatDate(payOrder.getIntoTime(), "yyyy-MM-dd HH:mm:ss"));
                //停留时间
                if (payOrder.getPayTime() != null && payOrder.getIntoTime() != null) {
                    long stayTime = (payOrder.getPayTime().getTime() - payOrder.getIntoTime().getTime()) / 1000;
                    rsp.setStayTime(DateUtil.formatTime(stayTime));
                }
            }
            rsp.setResult(MerchantCouponLssueRecordRsp.SUCCESS);
        } catch (Exception e) {
            rsp.setResult(MerchantBusinessRsp.FAIL);
            rsp.setStrError("获取支付成功信息异常！");
            logger.error("获取支付成功信息异常{}", e.getMessage());
        }
        return rsp;
    }

    @Override
    public ReturnInvoiceRsp returnInvoice(String qrcodeIds) {
        ReturnInvoiceRsp returnInvoiceRsp = new ReturnInvoiceRsp();
        returnInvoiceRsp.setResult(MerchantBusinessRsp.FAIL);
        try {
            if (StringUtils.isEmpty(qrcodeIds)) {
                returnInvoiceRsp.setStrError("优惠券标识无效！");
                return returnInvoiceRsp;
            }
            String[] qrcodeList = qrcodeIds.split(",");
            for (String ids : qrcodeList) {
                if (StringUtils.isNotEmpty(ids)) {
                    merchantCouponMapper.updateCouponById(Integer.parseInt(ids));
                }
            }
            returnInvoiceRsp.setResult(MerchantBusinessRsp.SUCCESS);
            returnInvoiceRsp.setStrError("退券成功！");
            logger.info("【退电子优惠券】成功 ids：,{}", qrcodeIds);
        } catch (Exception e) {
            returnInvoiceRsp.setStrError("退电子优惠券异常！");
            logger.error("【退电子优惠券】失败，失败原因：{}", e.getMessage());
            return returnInvoiceRsp;
        }
        return returnInvoiceRsp;
    }
}
